import { Button, Modal, Select } from 'antd'
import { DeleteFilled } from '@ant-design/icons'
import { useRef, useState } from 'react'
import { createScopeDetailItem, editScopeDetailItem, getMapList } from '@/api/shoppingCart.ts'
import { message } from '@hs-admin/utils/StaticMethod.ts'
import { commonSelectProps } from '@/views/ShoppingCart/commonProps.ts'

const useEditIndustryScope = () => {
  const parentId = useRef('')
  const selfId = useRef('')
  const callFun = useRef(() => {
    console.log('do nothing')
  })
  const [open, setOpen] = useState(false)

  const [isChoosing, setIsChoosing] = useState(false)
  const [mapOptions, setMapOptions] = useState([])

  const [mapValue, setMapValue] = useState<null | {
    label: string
    value: string
  }>(null)
  const [mapList, setMapList] = useState<
    Array<{
      name: string
      value: string
    }>
  >([])

  const searchMap = (word?: string) => {
    getMapList({
      keyword: word
    }).then((res) => {
      setMapOptions(
        (res.items ?? []).map((item) => ({
          label: item.name,
          value: String(item.map_id)
        }))
      )
    })
  }

  return {
    EditIndustryScope: (
      <Modal
        open={open}
        title="产业范围选择"
        onOk={async () => {
          if (selfId.current) {
            await editScopeDetailItem(selfId.current, {
              values: mapList
            })
          } else {
            await createScopeDetailItem({
              type: 'industry',
              sub_scope_id: parentId.current,
              values: mapList
            })
          }
          setOpen(false)
          callFun.current()
        }}
        onCancel={() => {
          setOpen(false)
        }}>
        <div className="flex flex-col gap-6 px-9">
          {mapList.map((item, index) => (
            <div key={item.value}>
              <div className="flex gap-1">
                <span className="flex-1">{item.name}</span>
                <DeleteFilled
                  onClick={() => {
                    setMapList((prevState) => prevState.toSpliced(index, 1))
                  }}
                />
              </div>
            </div>
          ))}
          {isChoosing ? (
            <div className="flex gap-4">
              <Select
                {...commonSelectProps}
                showSearch
                onSearch={searchMap}
                onFocus={() => {
                  searchMap()
                }}
                value={mapValue?.value}
                onChange={(_, option) => {
                  setMapValue(option)
                }}
                filterOption={false}
                className="flex-1"
                options={mapOptions}></Select>
              <Button
                type="primary"
                onClick={() => {
                  if (mapValue) {
                    if (mapList.some((item) => item.value === mapValue.value)) {
                      message.error('已存在')
                      return
                    }
                    setMapList((prevState) => [
                      ...prevState,
                      {
                        name: mapValue?.label,
                        value: mapValue?.value
                      }
                    ])
                    setMapValue(null)
                    setIsChoosing(false)
                  }
                }}>
                确定
              </Button>
              <Button
                onClick={() => {
                  setIsChoosing(false)
                }}>
                取消
              </Button>
            </div>
          ) : (
            <Button type={'primary'} onClick={() => setIsChoosing(true)}>
              + 添加图谱
            </Button>
          )}
        </div>
      </Modal>
    ),
    openModal: (
      parent: string,
      self: string,
      oldValues: Array<{
        name: string
        value: string
      }>,
      call: () => void
    ) => {
      console.log('建立')
      setMapValue(null)
      setIsChoosing(false)
      parentId.current = parent
      selfId.current = self
      callFun.current = call
      setMapList(oldValues)
      setOpen(true)
    }
  }
}

export default useEditIndustryScope
